package com.xuzhiguang.lightnat.client.proxy.handler;

import com.xuzhiguang.lightnat.client.transfer.TransferChannelPoolHolder;
import com.xuzhiguang.lightnat.common.manager.ProxyChannelManager;
import com.xuzhiguang.lightnat.common.manager.TransferChannelManager;
import com.xuzhiguang.lightnat.common.message.NatMessage;
import com.xuzhiguang.lightnat.common.message.transfer.DisconnectRequest;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class InactiveHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        log.debug("proxy channel inactive. channel:{}", ctx.channel());

        // 是否同步 disconnect 到 server
        Boolean syncDisconnect = ProxyChannelManager.getSyncDisconnect(ctx.channel());
        if (syncDisconnect == null || syncDisconnect) {
            Long transferId = ProxyChannelManager.getTransferId(ctx.channel());
            if (transferId != null) {
                Channel transferChannel = TransferChannelManager.getChannel(transferId);
                if (transferChannel != null) {


                    log.info("recycle transferChannel. channel:{}", transferChannel);
                    // 回收 transfer channel
                    TransferChannelManager.setSessionId(transferChannel, null);
                    TransferChannelPoolHolder.get().recycle(transferChannel);


                    // transfer 通知 server 断开连接
                    transferChannel.writeAndFlush(new NatMessage(new DisconnectRequest()));
                } else {
                    log.warn("transferChannel is null. transferId:{}", transferId);
                }
            }
        }


        super.channelInactive(ctx);
    }
}
